package com.example.starter.verticle;

import com.example.starter.conf.Constants;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.SqlClient;
import io.vertx.sqlclient.Tuple;

/**
 * @author yangkui
 */
public class RepositoryVerticle extends AbstractVerticle {
  public static final String REPOSITORY_EVENT_BUS_ADDRESS = "repository_event_bus";

  @Override
  public void start() {
    var conf = config().getJsonObject(Constants.REPOSITORY);

    MySQLConnectOptions connectOptions = new MySQLConnectOptions()
      .setHost(conf.getString(Constants.HOST))
      .setPort(conf.getInteger(Constants.PORT))
      .setUser(conf.getString(Constants.USERNAME))
      .setPassword(conf.getString(Constants.PASSWORD))
      .setDatabase(conf.getString(Constants.DATABASE));


    // Pool options
    PoolOptions poolOptions = new PoolOptions()
      .setMaxSize(5);

    // Create the client pool
    SqlClient client = Pool.pool(vertx, connectOptions, poolOptions);

    var consumer = vertx.eventBus().<JsonObject>consumer(REPOSITORY_EVENT_BUS_ADDRESS);
    consumer.handler(message -> {
      var json = message.body();
      var table = json.getString(Constants.TABLE);
      var schema = json.getString(Constants.SCHEMA);
      var prepareQuery = client.preparedQuery("SELECT * FROM information_schema.COLUMNS WHERE table_name =? AND table_schema =?");
      var rows = Future.await(prepareQuery.execute(Tuple.of(table, schema)));
      var arr = new JsonArray();
      for (Row row : rows) {
        arr.add(row.toJson());
      }
      var data = new JsonObject();
      data.put("%s.%s".formatted(schema, table), arr);
      message.reply(data);
    });
  }
}
